﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using LifeInSharePoint.Common;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.IO;

namespace LifeInSharePoint.Blog.Common.Receivers.ThumbnailGeneration
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class ThumbnailGeneration : SPItemEventReceiver
    {

        private Guid listID;
        private Guid itemID;
        private Guid siteID;
        private string thumbnailUrl;
        private SPListItem item;

        /// <summary>
        /// An item was added.
        /// </summary>
        public override void ItemAdded(SPItemEventProperties properties)
        {
            base.ItemAdded(properties);
            SPListItem folder = CheckAndCreateFolder(properties, "thumbs");

            try
            {
                base.EventFiringEnabled = false;

                item = properties.ListItem;
                listID = properties.ListId;
                itemID = properties.ListItem.UniqueId;
                siteID = properties.SiteId;



                SPFile file = properties.ListItem.File;
                string absUrl = (string)file.Item[SPBuiltInFieldId.EncodedAbsUrl];
                thumbnailUrl = (string)folder[SPBuiltInFieldId.EncodedAbsUrl] + "/" + file.Name;



                System.Threading.Thread updateThumbnailurl = new System.Threading.Thread(UpdateThumbnailUrl);
                updateThumbnailurl.Start();

                


                string extension = Path.GetExtension(absUrl);

                SPWeb web = properties.List.ParentWeb;

                //Get reference to the library
                SPList library = properties.ListItem.ParentList;

                //Copy Existing File then edit it
                properties.ListItem.CopyTo(thumbnailUrl);

                base.EventFiringEnabled = true;

                SPFile thumbfile = web.GetFile(thumbnailUrl);

                if (null != thumbfile)
                {
                    web.AllowUnsafeUpdates = true;
                    try
                    {
                        //The Memory stream to save the new image
                        MemoryStream savedImageStream = new MemoryStream();
                        //The Memory stream to load the existing image into
                        MemoryStream loadImageIntoStream = new MemoryStream(thumbfile.OpenBinary(), true);

                        //define the size of the thumbnail (to be configurable)
                        Size newSize = new Size(200, 200);

                        //Set the uploaded file into an image so you can resize
                        Image img = Image.FromStream(loadImageIntoStream);

                        Image resizedImg = SPImageHelper.resizeImage(img, newSize);

                        resizedImg.Save(savedImageStream, System.Drawing.Imaging.ImageFormat.Jpeg);


                        thumbfile.SaveBinary(savedImageStream, false);

                        thumbfile.Update();

                        thumbfile.CheckIn(string.Empty);


                    }
                    finally
                    {
                        web.AllowUnsafeUpdates = false;
                    }
                }
            }
            catch
            {
                //Do some exception handling 
                throw;
            }
        }

        private SPListItem CheckAndCreateFolder(SPItemEventProperties properties, string FileName)
        {
            SPList list = properties.ListItem.ParentList;
            SPListItem folder = null;
            bool folderExists = false;
            // Check to see if folder already exists, if not create it
            for (int i = 0; i < list.Folders.Count; i++)
            {
                if (list.Folders[i].Folder.Name == FileName)
                {
                    folder = list.Folders[i];
                    folderExists = true;
                }
            }

            if (!folderExists) // The folder does not exist so we create it and add the item
            {                
                folder = list.Items.Add(list.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, FileName);
                folder.Update();
            }

            return folder;
        }

        private void UpdateThumbnailUrl()
        {
            try
            {

                System.Threading.Thread.Sleep(10000);
                using (SPSite site = new SPSite(siteID))
                {
                    using (SPWeb web = site.OpenWeb())
                    {

                        SPList list = web.Lists[listID];
                        SPListItem item = list.Items[itemID];

                        item["LISPBlogGalleryThumbnail"] = thumbnailUrl;
                        item.SystemUpdate();
                    }

                }
            }
            catch (Exception ex)
            {
                
            }

        }
    }
}

